package mango.orm.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import mango.orm.Dao;
import mango.orm.DaoIterator;
import mango.orm.OrmException;
import mango.orm.OrmFactory;
import mango.orm.DBSession;
import mango.orm.DBSessionFactory;
import mango.orm.entity.Entity;



public class EntityIterator extends DaoIterator<Entity> {

    public EntityIterator(Dao dao, DBSession session, boolean selfClose, ResultSet rs, Class<? extends Entity> retType)
            throws SQLException {
        super(dao, session, selfClose, rs, retType);
    }

    @SuppressWarnings("unchecked")
    @Override
    public Entity next() {
        try {
            if (!this.hasNext) {
                throw new OrmException("not support next()");
            }
            Entity result = OrmFactory.getExtracter(this.dbType)
                    .extract(this.retType, this.rs);
//            if (result.getRowNum() == 0) {
//                result.setRowNum(this.rowNum);
//            }
            this.postNext();
            return result;
        }
        catch (Exception e) {
            if (this.selfClose) {
                DBSessionFactory.closeSession(session);
            }
            throw new OrmException(e);
        }
    }
}
